<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">


<meta name="google-site-verification" content="E9deYnivN5MuHMuIfiMZZfS0alv-d_0UjcwjBL79lGU" />



<meta name="baidu-site-verification" content="iHYWJxscwD" />










<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />



  <meta name="google-site-verification" content="true" />








  <meta name="baidu-site-verification" content="true" />







  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Python,学习笔记,量化投资,pyalgotrade,回测指标计算," />










<meta name="description" content="因为对前面计算回测指标的程序的准确性还有疑问，我决定再验证一次。验证的方法是找一个带数据的完整的程序，先实现其程序，再用它的数据和我的程序计算，对比一下二者的结果。在知乎上找到一篇，https:&#x2F;&#x2F;zhuanlan.zhihu.com&#x2F;p&#x2F;55425806 是用贵州茅台，工商银行和中国平安三只股票做回测。我照着其程序写了，计算结果与文章中的一致。接下来就用pyalgotrade框架和我自己的封装来">
<meta property="og:type" content="article">
<meta property="og:title" content="量化投资学习笔记05——检验计算回测指标程序">
<meta property="og:url" content="https://zwdnet.github.io/2020/01/01/%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B005%E2%80%94%E2%80%94%E6%A3%80%E9%AA%8C%E8%AE%A1%E7%AE%97%E5%9B%9E%E6%B5%8B%E6%8C%87%E6%A0%87%E7%A8%8B%E5%BA%8F/index.html">
<meta property="og:site_name" content="赵瑜敏的口腔医学专业学习博客">
<meta property="og:description" content="因为对前面计算回测指标的程序的准确性还有疑问，我决定再验证一次。验证的方法是找一个带数据的完整的程序，先实现其程序，再用它的数据和我的程序计算，对比一下二者的结果。在知乎上找到一篇，https:&#x2F;&#x2F;zhuanlan.zhihu.com&#x2F;p&#x2F;55425806 是用贵州茅台，工商银行和中国平安三只股票做回测。我照着其程序写了，计算结果与文章中的一致。接下来就用pyalgotrade框架和我自己的封装来">
<meta property="og:locale">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/05/01.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/05/02.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/05/03.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/05/04.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/05/05.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/05/06.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/05/01_x.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/05/02_x.png">
<meta property="og:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/wx.jpg">
<meta property="article:published_time" content="2020-01-01T08:20:03.000Z">
<meta property="article:modified_time" content="2020-08-30T05:52:04.000Z">
<meta property="article:author" content="赵瑜敏">
<meta property="article:tag" content="Python">
<meta property="article:tag" content="学习笔记">
<meta property="article:tag" content="量化投资">
<meta property="article:tag" content="pyalgotrade">
<meta property="article:tag" content="回测指标计算">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/05/01.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://zwdnet.github.io/2020/01/01/量化投资学习笔记05——检验计算回测指标程序/"/>





  <title>量化投资学习笔记05——检验计算回测指标程序 | 赵瑜敏的口腔医学专业学习博客</title>
  








<meta name="generator" content="Hexo 5.4.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">赵瑜敏的口腔医学专业学习博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/%20" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/%20" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/%20" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/%20" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://zwdnet.github.io/2020/01/01/%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B005%E2%80%94%E2%80%94%E6%A3%80%E9%AA%8C%E8%AE%A1%E7%AE%97%E5%9B%9E%E6%B5%8B%E6%8C%87%E6%A0%87%E7%A8%8B%E5%BA%8F/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/tx.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="赵瑜敏的口腔医学专业学习博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">量化投资学习笔记05——检验计算回测指标程序</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-01-01T08:20:03+00:00">
                2020-01-01
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84/" itemprop="url" rel="index">
                    <span itemprop="name">量化投资</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                  <span class="post-meta-divider">|</span>
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  2.9k
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  11
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>因为对前面计算回测指标的程序的准确性还有疑问，我决定再验证一次。验证的方法是找一个带数据的完整的程序，先实现其程序，再用它的数据和我的程序计算，对比一下二者的结果。<br>在知乎上找到一篇，<a target="_blank" rel="noopener" href="https://zhuanlan.zhihu.com/p/55425806">https://zhuanlan.zhihu.com/p/55425806</a> 是用贵州茅台，工商银行和中国平安三只股票做回测。我照着其程序写了，计算结果与文章中的一致。<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/05/01.png"><br>接下来就用pyalgotrade框架和我自己的封装来写了。因为pyalgotrade_tushare只能按整年进行数据抓取，把文章中的日期改为到2018年12月31日(而不是原文中的2019年1月18日)。<br>但是用我的程序算那些指标还是与文章里算的不对，尤其β值居然是0。我还是找现成的库吧。<br>找了一圈，发现一个我能用的:empyrical。但是尝试以后，发现还是有问题，如图:<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/05/02.png"><br>用pyalgotrade文档里的例子做测试，前面是pyalgotrade里的回测结果，然后用其计算的收益率作为输入，用empyrical库计算其它指标，最大回撤是一致的，αβ值不知道是否正确，夏普比率相差太多啦。<br>于是决定回到最基础的办法:自己编个数据，按照这些指标的定义手算，再用程序验证吧。<br>本文以下参考《量化投资:以python为工具》一书相关章节。<br>假设有股票test，初始价格为1，每天涨1元，一共10天。基准指数base初始价格也是1，每天涨0.5元，一共10天。第一天各买入1股，计算每天的收益率。为了保持一致，假定初始投入2.5元，再少pyalgotrade会报现金不足。<br>test.csv</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">Date,Open,Close,High,Low,Volume</span><br><span class="line"><span class="number">2019</span>-01-01,<span class="number">2.369</span>,<span class="number">1.0</span>,<span class="number">9</span>,<span class="number">0</span>,<span class="number">1877797.0</span></span><br><span class="line"><span class="number">2019</span>-01-02,<span class="number">2.358</span>,<span class="number">2.0</span>,<span class="number">9</span>,<span class="number">0</span>,<span class="number">4404445.0</span></span><br><span class="line"><span class="number">2019</span>-01-03,<span class="number">2.335</span>,<span class="number">3.0</span>,<span class="number">9</span>,<span class="number">0</span>,<span class="number">4834089.0</span></span><br><span class="line"><span class="number">2019</span>-01-04,<span class="number">2.27</span>,<span class="number">4.0</span>,<span class="number">9</span>,<span class="number">0</span>,<span class="number">1525888.0</span></span><br><span class="line"><span class="number">2019</span>-01-05,<span class="number">2.287</span>,<span class="number">5.0</span>,<span class="number">9</span>,<span class="number">0</span>,<span class="number">2050543.0</span></span><br><span class="line"><span class="number">2019</span>-01-06,<span class="number">2.28</span>,<span class="number">6.0</span>,<span class="number">9</span>,<span class="number">0</span>,<span class="number">3371288.0</span></span><br><span class="line"><span class="number">2019</span>-01-07,<span class="number">2.269</span>,<span class="number">7.0</span>,<span class="number">9</span>,<span class="number">0</span>,<span class="number">3701781.0</span></span><br><span class="line"><span class="number">2019</span>-01-08,<span class="number">2.255</span>,<span class="number">8.0</span>,<span class="number">9</span>,<span class="number">0</span>,<span class="number">4884821.0</span></span><br><span class="line"><span class="number">2019</span>-01-09,<span class="number">2.239</span>,<span class="number">9.0</span>,<span class="number">19</span>,<span class="number">0</span>,<span class="number">2509259.0</span></span><br><span class="line"><span class="number">2019</span>-01-<span class="number">10</span>,<span class="number">2.253</span>,<span class="number">10.0</span>,<span class="number">19</span>,<span class="number">0</span>,<span class="number">3339884.0</span></span><br><span class="line"><span class="number">2019</span>-01-<span class="number">10</span>,<span class="number">2.253</span>,<span class="number">10.0</span>,<span class="number">19</span>,<span class="number">0</span>,<span class="number">3339884.0</span></span><br></pre></td></tr></table></figure>
<p>base.csv</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">Date,Open,Close,High,Low,Volume</span><br><span class="line"><span class="number">2019</span>-01-01,<span class="number">2.369</span>,<span class="number">1.0</span>,<span class="number">9</span>,<span class="number">0</span>,<span class="number">1877797.0</span></span><br><span class="line"><span class="number">2019</span>-01-02,<span class="number">2.358</span>,<span class="number">1.5</span>,<span class="number">9</span>,<span class="number">0</span>,<span class="number">4404445.0</span></span><br><span class="line"><span class="number">2019</span>-01-03,<span class="number">2.335</span>,<span class="number">2.0</span>,<span class="number">9</span>,<span class="number">0</span>,<span class="number">4834089.0</span></span><br><span class="line"><span class="number">2019</span>-01-04,<span class="number">2.27</span>,<span class="number">2.5</span>,<span class="number">9</span>,<span class="number">0</span>,<span class="number">1525888.0</span></span><br><span class="line"><span class="number">2019</span>-01-05,<span class="number">2.287</span>,<span class="number">3.0</span>,<span class="number">9</span>,<span class="number">0</span>,<span class="number">2050543.0</span></span><br><span class="line"><span class="number">2019</span>-01-06,<span class="number">2.28</span>,<span class="number">3.5</span>,<span class="number">9</span>,<span class="number">0</span>,<span class="number">3371288.0</span></span><br><span class="line"><span class="number">2019</span>-01-07,<span class="number">2.269</span>,<span class="number">4.0</span>,<span class="number">9</span>,<span class="number">0</span>,<span class="number">3701781.0</span></span><br><span class="line"><span class="number">2019</span>-01-08,<span class="number">2.255</span>,<span class="number">4.5</span>,<span class="number">9</span>,<span class="number">0</span>,<span class="number">4884821.0</span></span><br><span class="line"><span class="number">2019</span>-01-09,<span class="number">2.239</span>,<span class="number">5.0</span>,<span class="number">9</span>,<span class="number">0</span>,<span class="number">2509259.0</span></span><br><span class="line"><span class="number">2019</span>-01-<span class="number">10</span>,<span class="number">2.253</span>,<span class="number">5.5</span>,<span class="number">9</span>,<span class="number">0</span>,<span class="number">3339884.0</span></span><br></pre></td></tr></table></figure>
<p>计算中只用Close一列，最低最高价也修改了，其它的保持原状，目的是使pyalgotrade框架能够使用数据。<br>接下来从收益和收益率开始计算。<br>资产的收益率是指投入某资产所能产生的收益与当初投资成本的比例。<br>收益率=投资收益/投资成本<br>期间投资收益=期末价格-期初价格+其它收益<br>期间收益率=期间收益/期初价格<br>每天为一期，为了跟pyalgotrade框架一致，第一天决策，次日才交易。<br>test的收益率<br>第一天: 2.5-2.5/2.5 = 0.0<br>第二天: 2.5-2.5/2.5 = 0.0<br>第三天: 3.5-2.5/2.5 = 0.4<br>第四天: 4.5-3.5/3.5 = 0.2857142857142857<br>以此类推。<br>base的收益率:<br>第一天: 2.5-2.5/2.5 = 0.0<br>第二天: 2.5-2.5/2.5 = 0.0<br>第三天: 3.0-2.5/2.5 = 0.2<br>第四天: 3.5-3.0/3.0 = 0.1666666666666667<br>以此类推。<br>现在用python算一下。<br>先读取数据</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 从文件中读取数据</span></span><br><span class="line">test_df = pd.read_csv(<span class="string">&quot;test.csv&quot;</span>, index_col = <span class="string">&quot;Date&quot;</span>)</span><br><span class="line">print(test_df)</span><br><span class="line">base_df = pd.read_csv(<span class="string">&quot;base.csv&quot;</span>, index_col = <span class="string">&quot;Date&quot;</span>)</span><br><span class="line">print(base_df)</span><br><span class="line"><span class="comment"># 提取收盘价信息</span></span><br><span class="line">test_close = test_df[<span class="string">&quot;Close&quot;</span>]</span><br><span class="line">base_close = base_df[[<span class="string">&quot;Close&quot;</span>]]</span><br><span class="line"><span class="comment"># test_close.name = &quot;Close&quot;</span></span><br><span class="line"><span class="comment"># base_close.name = &quot;Close&quot;</span></span><br><span class="line">print(test_close, base_close)</span><br><span class="line"><span class="comment"># 计算每日收益率</span></span><br><span class="line"><span class="comment"># 初始投资</span></span><br><span class="line">cash_test = <span class="number">2.5</span></span><br><span class="line">cash_base = <span class="number">2.5</span></span><br><span class="line"><span class="comment"># 每期市值</span></span><br><span class="line">position_test = []</span><br><span class="line">position_base = []</span><br><span class="line">print(test_close.values[<span class="number">0</span>], base_close.values[<span class="number">0</span>])</span><br><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="built_in">len</span>(test_close)):</span><br><span class="line">    <span class="keyword">if</span> i == <span class="number">0</span>:</span><br><span class="line">        position_test.append(cash_test)</span><br><span class="line">        position_base.append(cash_base)</span><br><span class="line">        <span class="keyword">continue</span></span><br><span class="line">    <span class="keyword">elif</span> i == <span class="number">1</span>:</span><br><span class="line">        cash_test = cash_test - test_close[<span class="number">0</span>]</span><br><span class="line">        cash_base = cash_base - base_close.values[<span class="number">0</span>][<span class="number">0</span>]</span><br><span class="line">    <span class="keyword">if</span> cash_test &lt;= <span class="number">0</span> <span class="keyword">or</span> cash_base &lt;= <span class="number">0</span>:</span><br><span class="line">        print(<span class="string">&quot;现金不足，退出&quot;</span>)</span><br><span class="line">    position_test.append(cash_test + test_close[i-<span class="number">1</span>])</span><br><span class="line">    position_base.append(cash_base + base_close.values[i-<span class="number">1</span>][<span class="number">0</span>])</span><br><span class="line"></span><br><span class="line">print(position_test, position_base)</span><br><span class="line">test_return = []</span><br><span class="line">base_return = []</span><br><span class="line">test_return.append(<span class="number">0.0</span>)</span><br><span class="line">base_return.append(<span class="number">0.0</span>)</span><br><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">1</span>, <span class="built_in">len</span>(position_test)):</span><br><span class="line">    print(i, position_test[i], position_test[i-<span class="number">1</span>])</span><br><span class="line">    test_return.append((position_test[i] - position_test[i-<span class="number">1</span>])/position_test[i-<span class="number">1</span>])</span><br><span class="line">    base_return.append((position_base[i] - position_base[i-<span class="number">1</span>])/position_base[i-<span class="number">1</span>])</span><br></pre></td></tr></table></figure>
<p>计算结果<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/05/03.png"><br>对了。接下来计算年化收益率<br>年化收益率是把当前收益率(日、周、月收益率等)换算成年收益率，方便投资人比较不同期限的投资。这只是理论上的收益率，并不是投资人真正能获得的收益率。<br>持有T期收益为Rt, 一年有m个单期，则年化收益率为(Rt/T)×m<br>如果考虑复利，年化收益率=(1+Rt)^(1/(T/m))-1</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 计算年化收益率</span></span><br><span class="line">np_test_return = np.array(test_return)</span><br><span class="line">np_base_return = np.array(base_return)</span><br><span class="line">annret_test = (<span class="number">1</span>+np_test_return).cumprod()[-<span class="number">1</span>]**(<span class="number">245</span>/<span class="number">311</span>) - <span class="number">1</span></span><br><span class="line">annret_base = (<span class="number">1</span>+np_base_return).cumprod()[-<span class="number">1</span>]**(<span class="number">245</span>/<span class="number">311</span>) - <span class="number">1</span></span><br><span class="line">print(annret_test, annret_base)</span><br><span class="line">print(<span class="string">&quot;empyrical&quot;</span>)</span><br><span class="line">annret_test_ep = ep.annual_return(np_test_return)</span><br><span class="line">annret_base_ep = ep.annual_return(np_base_return)</span><br><span class="line">print(annret_test_ep, annret_base_ep)</span><br></pre></td></tr></table></figure>
<p>结果<br>2.097306384013633 1.1227960188906434<br>empyrical里有计算年化收益率的函数，试试。<br>5080215298974669.0 28663443858.08141<br>差别好大，感觉年化收益率蛮坑的，理财，保险等机构都喜欢用这个概念，先略过吧。后面用不到。<br>接下来看风险指标<br>首先可以用收益率的标准差来衡量。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#衡量风险</span></span><br><span class="line"><span class="comment"># 标准差</span></span><br><span class="line">print(np_test_return.std(), np_base_return.std())</span><br></pre></td></tr></table></figure>
<p>结果<br>0.11597007874921565 0.06111509424879022<br>前者的风险更大。<br>最大回撤，因为我的数据就没有回撤，而且几个库计算的最大回撤值几乎一样，就不自己写了。用empyrical库试试。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 最大回撤</span></span><br><span class="line">print(ep.max_drawdown(np_test_return), ep.max_drawdown(np_base_return))</span><br></pre></td></tr></table></figure>
<p>结果都是0.0<br>现在来计算策略的α和β值，其来自资本资产定价模型(CAPM)，Rq为资产组合的收益，Rf为无风险资产收益，Rm为市场资产组合收益(一般以大盘指数代表)，有如下关系:<br>E(Rq) - Rf = βqm(E(Rm) - Rf)<br>即，β值为策略收益与无风险收益之差与和市场平均收益与无风险收益之差的比值。<br>βqm又等于σ(Rq,Rm)/σ²(Rm)，前者为资产组合收益率与市场投资组合收益率之间的协方差，后者为市场投资组合的方差，β值反映出投资组合的系统性风险。若β=1，则策略与市场的波动性是一致的，若β绝对值小于1，则策略的波动性小于市场，若β绝对值大于1，则策略的波动性大于市场。单只股票的期望收益是无风险收益加上系统性风险溢酬。非系统风险可以通过分散投资消除。<br>将模型写成不含期望值的形式:<br>Rit - Rft = α + β(Rmt - Rft) + ε<br>Rit,Rft,Rmt分别为个股收益率，无风险收益率和市场收益率，对这些资料进行线性回归，可以得到α和β值的估计值。β值可以解释个股过去收益率与风险的关系，根据这个模型，所有资产α值都应为0，若显著异于0，则个股有异常收益。Alpha值代表收益率胜过大盘的部分。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 计算αβ值</span></span><br><span class="line"><span class="comment"># 先将两个收益率合并到一起</span></span><br><span class="line">Ret = pd.merge(pd.DataFrame(base_return), pd.DataFrame(test_return),  left_index = <span class="literal">True</span>, right_index = <span class="literal">True</span>, how = <span class="string">&quot;inner&quot;</span>)</span><br><span class="line">print(Ret)</span><br><span class="line"><span class="comment"># 计算无风险收益</span></span><br><span class="line">rf = <span class="number">1.036</span>**(<span class="number">1</span>/<span class="number">360</span>) - <span class="number">1.0</span></span><br><span class="line">print(rf)</span><br><span class="line"><span class="comment"># 计算股票超额收益率和市场风险溢酬</span></span><br><span class="line">Eret = Ret - rf</span><br><span class="line">print(Eret)</span><br><span class="line"><span class="comment"># 接下来进行拟合</span></span><br><span class="line">model = sm.OLS(np_test_return, sm.add_constant(np_base_return))</span><br><span class="line">result = model.fit()</span><br><span class="line">print(result.summary())</span><br></pre></td></tr></table></figure>
<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/05/04.png"><br>计算结果，α为-0.0279，β为1.8462，再用empyrical算一遍。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">print(<span class="string">&quot;empyrical&quot;</span>)</span><br><span class="line">alpha, beta = ep.alpha_beta(np_test_return, np_base_return, <span class="number">0.036</span>)</span><br><span class="line">print(alpha, beta)</span><br></pre></td></tr></table></figure>
<p>计算结果<br>0.8273048650075308 1.8426052351694182<br>还是相差很多。β值很不确定，同一股票不同时期的β值相差很大。用历史数据计算β值，对投资的指导意义不大。所以，也许可以不用再纠结了。<br>最后算夏普值。<br>夏普比率就是一个可以同时对收益与风险加以综合考虑的三大经典指标之一。 投资中有一个常规的特 点，即投资标的的预期报酬越高，投资人所能忍受的波动风险越高；反之，预期报酬越低，波动风险也越低。所以理性的投资人选择投资标的与投资组合的主要目的为：在固定所能承受的风险下，追求最大的报酬；或在固定的预期报酬下，追求最低的风险。<br>。理性的投资者将选择并持有有效的投资组合，即那些在给定的风险水平下使期望回报最大化的投资组合，或那些在给定期望回报率的水平上使风险最小化的投资组合。解释起来非常简单，他认为投资者在建立有风险的投资组合时，至少应该要求投资回报达到无风险投资的回报，或者更多。<br>夏普比率目的是计算投资组合每承受一单位总风险，会产生多少的超额报酬。夏普指数代表投资人每多承担一分风险，可以拿到几分超额报酬；若为正值，代表基金报酬率高过波动风险；若为负值，代表基金操作风险大过于报酬率。这样一来，每个投资组合都可以计算Sharpe Ratio, 即投资回报与多冒风险的比例，这个比例越高，投资组合越佳。夏普比率没有基准点，因此其大小本身没有意义，只有在与其他组合的比较中才有价值。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 计算夏普比率</span></span><br><span class="line">sharpe = (np_test_return.mean() - <span class="number">0.03</span>)/np_test_return.std()*np.sqrt(<span class="number">252</span>)</span><br><span class="line">print(sharpe)</span><br></pre></td></tr></table></figure>
<p>结果<br>17.79285680812303<br>再用empyrical算一次<br>16.879786078470694<br>两个结果是基本一致的。<br>接下来，就再用pyalgotrade回测一下吧。<br>代码我就不往上放了，只放结果。<br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/05/05.png"><br><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/05/06.png"><br>还是有差异。尤其是α和β值。看了一下代码，在pyalgotrade的回测代码里增加了输出，发现成交价是2.36元，不是我想的2.0元。是因为这个原因吗？唉，不纠结了，就这样吧。用pyalgotrade回测算收益率、投资收益、夏普值，最大回撤等，用empyrical算α和β值。<br>本文代码：<br><a target="_blank" rel="noopener" href="https://github.com/zwdnet/MyQuant/tree/master/05">https://github.com/zwdnet/MyQuant/tree/master/05</a><br>自己算指标在index.py里，用pyalgotrade回测在pyat_index.py里。</p>
<p>补充:</p>
<p>终于发现哪里错了！是数据，pyalgotrade默认用开盘价交易，不是我以为的收盘价。把开盘价改了跟收盘价一样，结果就和我手算的一样了。β值也完全一样了，但是α值和夏普值还是有差别。貌似用框架算的要可靠一些。</p>
<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/05/01_x.png"></p>
<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/blog0178-QTLearn/05/02_x.png"></p>
<p>我发文章的三个地方，欢迎大家在朋友圈等地方分享，欢迎点“在看”。<br>我的个人博客地址：<a href="https://zwdnet.github.io/">https://zwdnet.github.io</a><br>我的知乎文章首页： <a target="_blank" rel="noopener" href="https://www.zhihu.com/people/zhao-you-min/posts">https://www.zhihu.com/people/zhao-you-min/posts</a><br>我的博客园博客地址： <a target="_blank" rel="noopener" href="https://www.cnblogs.com/zwdnet/">https://www.cnblogs.com/zwdnet/</a><br>我的微信个人订阅号：赵瑜敏的口腔医学学习园地</p>
<p><img src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/wx.jpg"></p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>欢迎打赏！感谢支持！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/mm_facetoface_collect_qrcode_1542944836634.png" alt=" 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/1542944857770.jpg" alt=" 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Python/" rel="tag"># Python</a>
          
            <a href="/tags/%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/" rel="tag"># 学习笔记</a>
          
            <a href="/tags/%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84/" rel="tag"># 量化投资</a>
          
            <a href="/tags/pyalgotrade/" rel="tag"># pyalgotrade</a>
          
            <a href="/tags/%E5%9B%9E%E6%B5%8B%E6%8C%87%E6%A0%87%E8%AE%A1%E7%AE%97/" rel="tag"># 回测指标计算</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/12/29/%E4%BD%A0%E7%9F%A5%E9%81%93%E7%89%99%E6%A0%B9%E7%9B%BE%E7%89%8C%E6%9C%AF%E5%90%97%EF%BC%9F/" rel="next" title="你知道牙根盾牌术吗？">
                <i class="fa fa-chevron-left"></i> 你知道牙根盾牌术吗？
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2020/01/04/%E6%A5%94%E7%BC%BA%E6%98%AF%E5%88%B7%E7%89%99%E5%AF%BC%E8%87%B4%E7%9A%84%E5%90%97%EF%BC%9F/" rel="prev" title="楔缺是刷牙导致的吗？">
                楔缺是刷牙导致的吗？ <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC80MTA2Mi8xNzU4Nw=="></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="https://zymblog-1258069789.cos.ap-chengdu.myqcloud.com/other/tx.jpg"
                alt="" />
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/%20%7C%7C%20archive">
              
                  <span class="site-state-item-count">452</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">29</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">544</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">本站版权归赵瑜敏所有，如欲转载请与本人联系。</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">1225.8k</span>
  
</div>









<div>
  <script type="text/javascript">var cnzz_protocol = (("https:" == document.location.protocol) ? " https://" : " http://");document.write(unescape("%3Cspan id='cnzz_stat_icon_1275447216'%3E%3C/span%3E%3Cscript src='" + cnzz_protocol + "s11.cnzz.com/z_stat.php%3Fid%3D1275447216%26online%3D1%26show%3Dline' type='text/javascript'%3E%3C/script%3E"));</script>
</div>

        







  <div style="display: none;">
    <script src="//s95.cnzz.com/z_stat.php?id=1275447216&web_id=1275447216" language="JavaScript"></script>
  </div>



        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  












  





  

  

  

  
  

  

  

  

  
</body>
</html>
